package com.rockcent.api.controller;

import com.rockcent.api.Prop;
import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.PromotionCode;
import com.rockcent.mall.lib.domain.enumclass.UploadFileBusinessType;
import com.rockcent.mall.lib.dto.PromotionCodeDto;
import com.rockcent.mall.lib.dto.QrCodeDto;
import com.rockcent.mall.lib.dto.UploadImageFileDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.PromotionCodeRepository;
import com.rockcent.service.PromotionCodeService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * Created by marco on 2017/8/2.
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class PromotionCodeController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(PromotionCodeController.class);

    @Autowired
    private BaseUserHelper userHelper;
    @Autowired
    private PromotionCodeRepository promotionCodeRepository;
    @Autowired
    private Prop prop;
    @Autowired
    private QRCodeHelper qrCodeHelper;
    @Autowired
    private PromotionCodeService promotionCodeService;

    /**
     * @api {post} /v1/mall/promotioncode/save M端 推广码保存
     * @apiGroup MALL_PROMOTIONCODE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} name 名称 <code>必要参数</code>
     * @apiParam {String} remark 备注 <code>必要参数</code>
     *
     * @apiSuccess {Long} id 推广码ID
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} remark 备注
     * @apiSuccess {String} codeDefault 是否默认 (是:YES,否:NO)
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 2,
     *     "version": 0,
     *     "mallId": 51,
     *     "name": "test",
     *     "remark": "test123"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_PROMOTIONCODE_SAVE, method = RequestMethod.POST)
    public JsonResult save(@RequestBody PromotionCodeDto promotionCodeDto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if(userDto.mall == null || userDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            if(StringUtils.isEmpty(promotionCodeDto.getName())) {
                jsonResult.remind("name 不能为空", log);
                return;
            }
//            if(StringUtils.isEmpty(promotionCodeDto.getRemark())) {
//                jsonResult.remind("remark 不能为空", log);
//                return;
//            }
            PromotionCode pcode = promotionCodeRepository.findByMallIdAndCodeDefault(userDto.mall.getId(), Whether.YES);
            PromotionCode promotionCode = new PromotionCode();
            promotionCode.setMallId(userDto.mall.getId());
            promotionCode.setName(promotionCodeDto.getName());
            promotionCode.setRemark(promotionCodeDto.getRemark());
            promotionCode.setCodeDefault(pcode==null?Whether.YES:Whether.NO);
            jsonResult.data = promotionCodeRepository.save(promotionCode);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/promotioncode/del M端 推广码删除
     * @apiGroup MALL_PROMOTIONCODE
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} id 推广码ID <code>必要参数</code>
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_PROMOTIONCODE_DEL, method = RequestMethod.PUT)
    public JsonResult del(@RequestBody PromotionCodeDto promotionCodeDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            if (promotionCodeDto.getId() == null) {
                jsonResult.remind("推广码id 不能为空", log);
                return;
            }
            PromotionCode promotionCode = promotionCodeRepository.findByIdAndMallId(promotionCodeDto.getId(),userInfoDto.mall.getId());
            if(promotionCode == null) {
                jsonResult.remind("推广码记录 不存在", log);
                return;
            }
            if(promotionCode.getCodeDefault()!=null && promotionCode.getCodeDefault()==Whether.YES) {
                jsonResult.remind("默认推广码不可删除", log);
                return;
            }
            promotionCodeRepository.delete(promotionCode);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/promotioncode/list M端 推广码列表
     * @apiGroup MALL_PROMOTIONCODE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} name 名称
     * @apiParam {String} startDate 起始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize
     *
     * @apiSuccess {Long} id 推广码ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} viewCount 访问闪数
     * @apiSuccess {Long} customerCount 访问人数
     * @apiSuccess {Long} saleCount 售出数
     * @apiSuccess {Long} verifyCount 核销数
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} remark 备注
     * @apiSuccess {String} codeDefault 是否默认 (是:YES,否:NO)
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "id": 1,
     *         "dateCreated": "2017-08-02 14:46:17",
     *         "mallId": 51,
     *         "name": "test",
     *         "remark": "test123"
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_PROMOTIONCODE_LIST, method = RequestMethod.GET)
    public JsonResult list(HttpServletRequest request, PromotionCodeDto promotionCodeDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
            }
            promotionCodeDto.setMallId(userInfoDto.mall.getId());
            PageResult<PromotionCodeDto> pageResult = promotionCodeRepository.findPromotionCodes(promotionCodeDto,this.getPage(promotionCodeDto.getPageNo(), promotionCodeDto.getPageSize()));
            pageResult.data.stream().map(promotionCode -> {
                promotionCodeDto.setId(promotionCode.getId());
                Long viewCount = 0L;
                Long customerCount = 0L;
                Long saleCount = 0L;
                Long verifyCount = 0L;
                PromotionCodeDto pCode = promotionCodeService.visitPageStatistics(promotionCodeDto);
                if(pCode!=null) {
                    viewCount = pCode.getViewCount();
                    customerCount = pCode.getCustomerCount();
                }
                PromotionCodeDto proCode = promotionCodeService.promotionCodeStatistics(promotionCodeDto);
                if(proCode!=null) {
                    saleCount = proCode.getSaleCount();
                    verifyCount = proCode.getVerifyCount();
                }
                promotionCode.setSaleCount(saleCount==null?0L:saleCount);
                promotionCode.setVerifyCount(verifyCount==null?0L:verifyCount);
                promotionCode.setViewCount(viewCount==null?0L:viewCount);
                promotionCode.setCustomerCount(customerCount==null?0L:customerCount);
                return promotionCode;
            }).collect(Collectors.toList());
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/promotioncode/info M端 推广码详情
     * @apiGroup MALL_PROMOTIONCODE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiSuccess {Long} id 推广码ID
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": "http://uploads.rockcent.com/local/mall/promote/20178/21642105163f0e9539-5e5f-41db-b670-2467f52882c3.jpg"
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_PROMOTIONCODE_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request, PromotionCodeDto promotionCodeDto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userDto.mall == null || userDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            if (promotionCodeDto.getId() == null) {
                jsonResult.remind("推广码id 不能为空", log);
                return;
            }
            PromotionCode promotionCode = promotionCodeRepository.findByIdAndMallId(promotionCodeDto.getId(),userDto.mall.getId());
            if(promotionCode == null) {
                jsonResult.remind("推广码记录 不存在", log);
                return;
            }
            StringBuffer url = new StringBuffer();
            url.append("http://");
            QrCodeDto qrCodeDto = new QrCodeDto();
            qrCodeDto.setId(userDto.getId());
            qrCodeDto.setMallId(userDto.mall.getId());
            UploadImageFileDto uploadImageFileDto = qrCodeHelper.showQRCode(promotionCode.getId(),qrCodeDto, url.toString(), "channelSendOutQR.jpg", UploadFileBusinessType.MALL_PROMOTE, prop.env, prop.aliyunOssBucketName, prop.domainUploadsHttp);
            String path="";
            if(uploadImageFileDto!=null) {
                path=uploadImageFileDto.getPath();
                promotionCode.setPromoteUrl(path);
                promotionCodeRepository.save(promotionCode);
            }
            jsonResult.data = path;
        };
        return doing.go(request, log);
    }
}
